<template>
  <div class="dashboard-container">
    <el-card class="dashboard-card">
      <template #header>
        <div class="card-header">
          <span>健康数据概览</span>
        </div>
      </template>
      
      <div class="dashboard-content">
        <!-- 昨日健康分析 -->
        <el-card class="analysis-card" style="margin-bottom: 20px;">
          <template #header>
            <div class="card-header">
              <span>昨日健康分析</span>
            </div>
          </template>
          <div class="analysis-content">
            <p v-if="yesterdayAnalysis">{{ yesterdayAnalysis }}</p>
            <p v-else>暂无分析数据</p>
          </div>
        </el-card>
        
        <!-- 统计卡片 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon bg-primary">
                  <el-icon><User /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stats.bodyRecordCount }}</div>
                  <div class="stat-label">身体指标记录</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon bg-success">
                  <el-icon><Food /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stats.eatingRecordCount }}</div>
                  <div class="stat-label">饮食记录</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon bg-warning">
                  <el-icon><Moon /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stats.sleepRecordCount }}</div>
                  <div class="stat-label">睡眠记录</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon bg-info">
                  <el-icon><Basketball /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stats.sportsRecordCount }}</div>
                  <div class="stat-label">运动记录</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 图表区域 -->
        <el-row :gutter="20" class="charts-row">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>身体指标趋势</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="bodyChartRef" class="chart-wrapper"></div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>饮食热量统计</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="eatingChartRef" class="chart-wrapper"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 最近记录 -->
        <el-row :gutter="20" class="records-row">
          <el-col :span="12">
            <el-card class="records-card">
              <template #header>
                <div class="card-header">
                  <span>最近身体指标记录</span>
                </div>
              </template>
              <el-table :data="recentBodyRecords" style="width: 100%">
                <el-table-column prop="record_date" label="记录日期" width="120">
                    <template #default="scope">
                        {{ formatDateString(scope.row.record_date) }}
                    </template>
                </el-table-column>
                <el-table-column prop="weight" label="体重(kg)" width="100" />
                <el-table-column prop="bmi" label="BMI" width="100" />
                <el-table-column prop="high_pressure" label="高压" width="100" />
                <el-table-column prop="low_pressure" label="低压" width="100" />
              </el-table>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card class="records-card">
              <template #header>
                <div class="card-header">
                  <span>最近运动记录</span>
                </div>
              </template>
              <el-table :data="recentSportsRecords" style="width: 100%">
                <el-table-column prop="record_date" label="记录日期" width="120">
                    <template #default="scope">
                        {{ formatDateString(scope.row.record_date) }}
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="运动类型" width="120" />
                <el-table-column prop="during" label="时长(分钟)" width="120" />
                <el-table-column prop="calorie" label="消耗热量(kcal)" width="120" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { 
  getBodyRecords, 
  getSportsRecords,
  getUserHealthStats,
  getBodyRecordsForChart,
  getEatingRecordsForChart,
  getUserYesterdayAnalysis
} from '@/api/health'
import { formatDateString } from '@/utils'
import type { BodyRecord, SportsRecord } from '@/types/health'

// 统计数据
const stats = reactive({
  bodyRecordCount: 0,
  eatingRecordCount: 0,
  sleepRecordCount: 0,
  sportsRecordCount: 0
})

// 昨日健康分析
const yesterdayAnalysis = ref('')

// 最近记录
const recentBodyRecords = ref<BodyRecord[]>([])
const recentSportsRecords = ref<SportsRecord[]>([])

// 图表引用
const bodyChartRef = ref<HTMLDivElement | null>(null)
const eatingChartRef = ref<HTMLDivElement | null>(null)

// ECharts实例
let bodyChartInstance: echarts.ECharts | null = null
let eatingChartInstance: echarts.ECharts | null = null

// 获取统计数据
const fetchStats = async () => {
  try {
    const response: any = await getUserHealthStats()
    stats.bodyRecordCount = response.bodyRecordCount
    stats.eatingRecordCount = response.eatingRecordCount
    stats.sleepRecordCount = response.sleepRecordCount
    stats.sportsRecordCount = response.sportsRecordCount
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

// 获取昨日健康分析
const fetchYesterdayAnalysis = async () => {
  try {
    const response: any = await getUserYesterdayAnalysis()
    yesterdayAnalysis.value = response.analysis_result || '暂无分析数据'
  } catch (error) {
    // 如果没有分析数据，显示默认消息
    yesterdayAnalysis.value = '暂无分析数据'
  }
}

// 获取最近身体指标记录
const fetchRecentBodyRecords = async () => {
  try {
    const response: any = await getBodyRecords({
      page: 1,
      page_size: 5
    })
    recentBodyRecords.value = response.results
  } catch (error) {
    ElMessage.error('获取身体指标记录失败')
  }
}

// 获取最近运动记录
const fetchRecentSportsRecords = async () => {
  try {
    const response: any = await getSportsRecords({
      page: 1,
      page_size: 5
    })
    recentSportsRecords.value = response.results
  } catch (error) {
    ElMessage.error('获取运动记录失败')
  }
}

// 获取身体指标图表数据
const fetchBodyChartData = async () => {
  try {
    const response: any = await getBodyRecordsForChart({
      page: 1,
      page_size: 30
    })
    
    // 处理数据用于图表展示
    const records = response.results
    const dates = records.map((record: BodyRecord) => record.record_date)
    const weights = records.map((record: BodyRecord) => record.weight)
    const bmis = records.map((record: BodyRecord) => record.bmi)
    const highPressures = records.map((record: BodyRecord) => record.high_pressure)
    
    // 更新图表
    updateBodyChart(dates, weights, bmis, highPressures)
  } catch (error) {
    ElMessage.error('获取身体指标图表数据失败')
  }
}

// 更新身体指标图表
const updateBodyChart = (
  dates: string[], 
  weights: number[], 
  bmis: number[], 
  highPressures: number[]
) => {
  if (bodyChartRef.value) {
    // 销毁之前的实例
    if (bodyChartInstance) {
      bodyChartInstance.dispose()
    }
    
    // 初始化新的实例
    bodyChartInstance = echarts.init(bodyChartRef.value)

    // 格式化日期
    const formattedDates = dates.map(date => {
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    })
    
    // 图表配置
    const option = {
      title: {
        text: '身体指标趋势'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['体重', 'BMI', '高压']
      },
      xAxis: {
        type: 'category',
        data: formattedDates
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '体重',
          type: 'line',
          data: weights,
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: 'BMI',
          type: 'line',
          data: bmis,
          smooth: true,
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '高压',
          type: 'line',
          data: highPressures,
          smooth: true,
          itemStyle: {
            color: '#E6A23C'
          }
        }
      ]
    }
    
    // 设置配置项
    bodyChartInstance.setOption(option)
  }
}

// 获取饮食记录图表数据
const fetchEatingChartData = async () => {
  try {
    const response: any = await getEatingRecordsForChart({
      page: 1,
      page_size: 30
    })
    
    // 处理数据用于图表展示
    const records = response.results
    const dates = records.map((record: any) => record.record_date)
    const calories = records.map((record: any) => record.calorie)
    
    // 更新图表
    updateEatingChart(dates, calories)
  } catch (error) {
    ElMessage.error('获取饮食记录图表数据失败')
  }
}

// 更新饮食热量图表
const updateEatingChart = (dates: string[], calories: number[]) => {
  if (eatingChartRef.value) {
    // 销毁之前的实例
    if (eatingChartInstance) {
      eatingChartInstance.dispose()
    }
    
    // 初始化新的实例
    eatingChartInstance = echarts.init(eatingChartRef.value)

    // 格式化日期
    const formattedDates = dates.map(date => {
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    })
    
    // 图表配置
    const option = {
      title: {
        text: '饮食热量统计'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['热量摄入(kcal)']
      },
      xAxis: {
        type: 'category',
        data: formattedDates
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '热量摄入(kcal)',
          type: 'bar',
          data: calories,
          itemStyle: {
            color: '#409EFF'
          }
        }
      ]
    }
    
    // 设置配置项
    eatingChartInstance.setOption(option)
  }
}

// 初始化所有图表
const initCharts = () => {
  fetchBodyChartData()
  fetchEatingChartData()
}

// 窗口大小改变时重置图表
const handleResize = () => {
  if (bodyChartInstance) {
    bodyChartInstance.resize()
  }
  if (eatingChartInstance) {
    eatingChartInstance.resize()
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStats()
  fetchYesterdayAnalysis()
  fetchRecentBodyRecords()
  fetchRecentSportsRecords()
  initCharts()
  
  // 添加窗口大小改变监听
  window.addEventListener('resize', handleResize)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  // 移除窗口大小改变监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁ECharts实例
  if (bodyChartInstance) {
    bodyChartInstance.dispose()
    bodyChartInstance = null
  }
  if (eatingChartInstance) {
    eatingChartInstance.dispose()
    eatingChartInstance = null
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-card {
  min-height: calc(100vh - 100px);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.analysis-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.analysis-content {
  min-height: 100px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.bg-primary {
  background-color: #409eff;
}

.bg-success {
  background-color: #67c23a;
}

.bg-warning {
  background-color: #e6a23c;
}

.bg-info {
  background-color: #909399;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #999;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-container {
  height: 300px;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
}

.records-row {
  margin-bottom: 20px;
}

.records-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>